// 城市信息基本处理函数模块

const db = require('../mysql/index')


// 获取省市区
exports.getCity = (req, res) => {
    // 获取省
    const data = req.body
    if (data.type === 'province') {
        const getProvinceSql = 'SELECT * from province'
        db.query(getProvinceSql, (err, result) => {
            if (err) return res.cc(err);
            if (result.length === 0) return res.cc('获取省份数据失败')
            return res.send({
                code: 200,
                message: '获取省份数据成功',
                data: result
            })
        })
    // 获取市
    } else if (data.type === 'city' && data.province_code) {
        const getCitySql = 'SELECT * from city WHERE city_code like ? ;'
        // 省份开头的数字
        const province_code = data.province_code.slice(0, 2) + '%'
        db.query(getCitySql, province_code, (err, result) => {
            if (err) return res.cc(err);
            if (result.length === 0) return res.cc('获取市级数据失败或该市不存在');
            return res.send({
                code: 200,
                message: '获取市级数据成功',
                data: result
            })
        })
    // 获取区县
    } else if (data.type === 'area' && data.city_code) {
        const getAreaSql = 'SELECT * from area WHERE area_code like ? ;'
        // 对直辖市特殊处理
        const city = ['110000', '120000', '500000', '310000']
        if (city.includes(data.city_code)) {
            var city_code = data.city_code.slice(0, 3) + '%'
        } else {
            // 区县开头的数字
            var city_code = data.city_code.slice(0, 4) + '%'
        }
        db.query(getAreaSql, city_code, (err, result) => {
            if (err) return res.cc(err);
            if (result.length === 0) return res.cc('获取区县数据失败')
            // 去空格
            result.forEach(item => {
                item.area_name = item.area_name.trim()
            })
            return res.send({
                code: 200,
                message: '获取区县数据成功',
                data: result
            })
        })
    } else {
        return res.cc('请先获取上级数据');
    }
}
